package com.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.pojo.MovieList;
import com.pojo.ProgramCategory;
import com.pojo.Special;
import com.pojo.SpecialFilmList;
import com.service.DyService;
import com.service.DyTypeService;
import com.service.SpecialFilmListService;
import com.service.SpecialService;
import com.util.DesUtil;
import com.util.HardUtil;
import com.util.MD5Util;
import com.util.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.*;

@SuppressWarnings("ALL")
@Component("TimeTaskUpdateSpecialService")
public class TimeTaskUpdateSpecialService {


    @Value("${server.port}")
    private String port;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    @Qualifier("StringRedisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private DyTypeService dyTypeService;

    @Autowired
    private DyService dyService;

    @Value("${server.url}")
    private String server;

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private SpecialService specialService;

    @Autowired
    private SpecialFilmListService specialFilmListService;

    @Autowired

    @Value("${dy.tmp}")
    private String tmp;

    @Value("${dy.home}")
    private String home;

    private String downImage(String img, boolean rename) {

        File baseImage = new File(home + "/images");
        if (baseImage.exists() == false) {
            baseImage.mkdir();
        }
        String dir = StringUtils.getDir(img);
        String filename = StringUtils.getFilename(img);

        File imageBaseFile = new File(baseImage + dir);
        if (imageBaseFile.exists()) {
            imageBaseFile.mkdirs();
        }

        if (rename==false)
        {
            File fileImage = new File(imageBaseFile,filename);
            if (fileImage.exists()){
                return null;
            }
        }


        String newfilename = IdUtil.fastSimpleUUID() + ".png";
        String url = server + img;
        if (img.startsWith("http://") == true) {
            url = img;
        }


        try {
            if (rename) {
                File downfilename = new File(baseImage, newfilename);
                HttpUtil.downloadFile(url, downfilename);
            } else {
                File downfilename = new File(imageBaseFile, filename);
                HttpUtil.downloadFile(url, downfilename);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return newfilename;
    }



    private List<Special> removeAllSpecial(List<Special> src, List<Special> target) {
        LinkedList<Special> result = new LinkedList<Special>(src); //大集合用linkedlist
        HashSet<Special> targetHash = new HashSet<Special>(target); //小集合用hashset
        Iterator<Special> iter = result.iterator(); //采用Iterator迭代器进行数据的操作

        while (iter.hasNext()) {
            if (targetHash.contains(iter.next())) {
                iter.remove();
            }
        }
        return result;
    }



    private List<SpecialFilmList> removeAllSpecialFilm(List<SpecialFilmList> src, List<SpecialFilmList> target) {
        LinkedList<SpecialFilmList> result = new LinkedList<SpecialFilmList>(src); //大集合用linkedlist
        HashSet<SpecialFilmList> targetHash = new HashSet<SpecialFilmList>(target); //小集合用hashset
        Iterator<SpecialFilmList> iter = result.iterator(); //采用Iterator迭代器进行数据的操作

        while (iter.hasNext()) {
            if (targetHash.contains(iter.next())) {
                iter.remove();
            }
        }
        return result;
    }



    /**
     * 更新专题
     */
    @Scheduled(cron = "25 1/5 * * * ?")
    public synchronized void updateSpecial() {
        try {
            String spec_url = server + "api/v1/special/checkAllAvailableTopics";
            String response = restTemplate.getForObject(spec_url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(response);
            if (jsonObject != null) {
                int code = jsonObject.getInteger("code");
                if (code != 200) {
                    System.out.println(jsonObject.getString("msg"));
                    return;
                }
                //本地专题
                List<Special> localSpec = specialService.list();
                //获取远程节目列表
                List<Special> remoteSpecial = jsonObject.parseArray(jsonObject.getString("data"), Special.class);
                //要新增的专题
                List<Special> addSpec = removeAllSpecial(remoteSpecial, localSpec);
                //专题图片下载
                File file = new File(home + "/images");
                if (file.exists() == false) {
                    file.mkdir();
                }
                for (Special s : addSpec) {
                    downImage(s.getPicture(), false);
                    downImage(s.getBackground_picture(), false);
                }


                specialService.saveBatch(addSpec);
                //要删除的专题
                List<Special> removeSpec = removeAllSpecial(localSpec, remoteSpecial);
                for (Special s : removeSpec) {
                    specialService.removeById(s.getId());
                }

                //专题更新
                List<Special> list = specialService.list();
                for (Special s : list) {
                    long id = s.getId();
                    for (Special r : remoteSpecial) {
                        if (id == r.getId()) {

                            String image1 = r.getBackground_picture();
                            String image2 = r.getPicture();

                            BeanUtil.copyProperties(r, s);
                            specialService.updateById(s);
                            downImage(image1, false);
                            downImage(image2, false);
                            break;
                        }
                    }
                }

            }

            //api/v1/getAllMovieType

            //------------  获取所有专题 ---------------------------------------------//
            String spec_film_url = server + "api/v1/special/getAllFilmBySpecial";
            String response_film = restTemplate.getForObject(spec_film_url, String.class);
            JSONObject jsonObject_film = JSONObject.parseObject(response_film);

            if (jsonObject_film != null) {
                int code = jsonObject_film.getInteger("code");
                if (code != 200) {
                    System.out.println(jsonObject_film.getString("msg"));
                    return;
                }


                //本地专题电影
                List localSpecFilm = specialFilmListService.list();
                //获取远程节目列表
                List<SpecialFilmList> remoteSpecFilm = jsonObject_film.parseArray(jsonObject_film.getString("data"), SpecialFilmList.class);

                //要新增的专题电影
                List<SpecialFilmList> addSpecFilm = removeAllSpecialFilm(remoteSpecFilm, localSpecFilm);
                specialFilmListService.saveBatch(addSpecFilm);
                //要删除的专题
                List<SpecialFilmList> removeSpecFilm = removeAllSpecialFilm(localSpecFilm, remoteSpecFilm);
                for (SpecialFilmList s : removeSpecFilm) {
                    specialFilmListService.removeById(s.getId());
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
